import Vue from 'vue'
import Vuex from 'vuex'

import cart from './modules/cart.js'
import address from './modules/address.js'
import order from './modules/order.js'
import loginInfo from './modules/loginInfo.js'

Vue.use(Vuex)

const myPlugin = store=>{
  store.subscribe((mutations,state)=>{
    // 操作数据
    // 每当调用mutations中的任意方法时触发
    // 因为是分模块的，所以都要去先判断是哪个模块的mutations
    // mutations.type返回对应的模块名称
    console.log(mutations);
    if(mutations.type.startsWith('loginInfo/')) {
      // 每一次的mutations操作都会触发这个setItem
      window.localStorage.setItem("loginInfo",JSON.stringify(state.loginInfo.userInfo))
    }
    if(mutations.type.startsWith('cart/')) {
      // 每一次的mutations操作都会触发这个setItem
      window.localStorage.setItem("cartArr",JSON.stringify(state.cart.cartArr))
    }
    if(mutations.type.startsWith('address/')) {
      // 每一次的mutations操作都会触发这个setItem
      window.localStorage.setItem("addressList",JSON.stringify(state.address.addressList))
      window.localStorage.setItem("defaultAddress",JSON.stringify(state.address.defaultAddress))
    }
    if(mutations.type.startsWith('order/')) {
      window.localStorage.setItem("orderList",JSON.stringify(state.order.orderList))
    }
  })
}

export default new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
    loginInfo,
    cart,
    address,
    order,
  },
  plugins:[myPlugin]
})
